<?php

namespace common\models\goods;

use Yii;
use common\models\product\Product;
use common\models\product\ProductPrices;

/**
 * 这个模型基于表 "{{%goods}}" 生成。
 *
 * @property integer $id
 * @property string $name
 * @property integer $category_id
 * @property integer $goods_type
 * @property integer $brand_id
 * @property string $img
 * @property integer $is_on_sale
 * @property integer $is_del
 * @property integer $add_time
 * @property integer $last_update
 * @property string $remark
 * @property integer $supplier_id
 * @property string $pack_unit
 * @property string $class_id
 * @property string $price_retail
 * @property string $price_mix
 * @property string $price_pack
 * @property integer $is_stock_disable
 * @property integer $is_auto_sale_on
 * @property integer $is_auto_sale_off
 * @property integer $stock
 */
class Goods extends \common\models\AR {

    public $modelName = '商品';

    const SELL_TYPE_RETAIL = 1;
    const SELL_TYPE_MIX = 2;
    const SELL_TYPE_PACK = 3;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%goods}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'category_id', 'supplier_id'], 'required'],
            [['category_id', 'goods_type', 'brand_id', 'is_on_sale', 'is_del', 'add_time', 'last_update', 'supplier_id', 'is_stock_disable', 'is_auto_sale_on', 'is_auto_sale_off', 'stock', 'factory_id', 'stock_lock'], 'integer'],
            [['price_retail', 'price_mix', 'price_pack'], 'number'],
            [['name', 'class_id'], 'string', 'max' => 50],
            [['img'], 'string', 'max' => 80],
            [['remark'], 'string', 'max' => 45],
            [['pack_unit'], 'string', 'max' => 8],
            [['goods_type', 'brand_id', 'is_del', 'is_stock_disable', 'stock', 'is_auto_sale_on', 'is_auto_sale_off', 'factory_id'], 'default', 'value' => 0],
            [['is_on_sale'], 'default', 'value' => 1],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '商品名称',
            'category_id' => '所属类目',
            'goods_type' => '商品类型',
            'brand_id' => '商品品牌',
            'img' => '商品图片',
            'is_on_sale' => '销售状态',
            'is_del' => '已删除',
            'add_time' => '添加时间',
            'last_update' => '最后编辑时间',
            'remark' => '备注',
            'supplier_id' => '所属供应商',
            'pack_unit' => '包装单位',
            'class_id' => '分类',
            'price_retail' => '零售价',
            'price_mix' => '混批价',
            'price_pack' => '整箱价',
            'is_stock_disable' => '下单时，不检测商品库存',
            'is_auto_sale_on' => '有库存时，自动上架',
            'is_auto_sale_off' => '没有库存时，自动下架',
            'stock' => '商品总数',
            'factory_id' => '所属厂家',
        ];
    }

    public function beforeSave($insert) {
        if (!parent::beforeSave($insert)) {
            return FALSE;
        }
        if ($this->isNewRecord) {
            $this->add_time = time();
        } else {
            $this->last_update = time();
        }
        return true;
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        
        //同步商品信息
    }

    public function afterDelete() {
        parent::afterDelete();
        $condition = 'goods_id=:goods_id';
        $params = [':goods_id' => $this->id];
        $goodsInfo = GoodsInfo::find()->where($condition, $params)->one();
        $goodsInfo && $goodsInfo->delete();

        $attrVals = GoodsAttrVal::find()->where($condition, $params)->all();
        foreach ($attrVals as $item) {
            $item->delete();
        }

        $Gallerys = GoodsGallery::find()->where($condition, $params)->all();
        foreach ($Gallerys as $item) {
            $item->delete();
        }

        $products = Product::find()->where($condition, $params)->all();
        foreach ($products as $item) {
            $item->delete();
        }
    }

    /**
     * 商品扩展信息
     * @return GoodsGallery 
     */
    public function getInfo() {
        return $this->hasOne(GoodsInfo::className(), ['goods_id' => 'id']);
    }

    /**
     * 商品相册
     * @return [GoodsGallery]
     */
    public function getGallery() {
        return GoodsGallery::find()->where(['goods_id' => $this->id])->orderBy(['sort' => SORT_DESC])->all();
    }

    /**
     * 获取货品信息集合
     * @return [Product]
     */
    public function getProducts() {
        return $this->hasMany(Product::className(), ['goods_id' => 'id']);
    }

    /**
     * 获取商品规格
     * @return type
     */
    public function getSku() {
        return $this->hasMany(GoodsAttrVal::className(), ['goods_id' => 'id']);
    }

    /**
     * 更新商品的零售价、混批价、整箱价
     * @param intval $type 更新价格类型 默认为0，更新所有价格类型
     * @return boolean
     */
    public function updatePrices($type = 0) {
        $allType = [Goods::SELL_TYPE_RETAIL, Goods::SELL_TYPE_MIX, Goods::SELL_TYPE_PACK];
        $update = [];
        if ($type == 0) {
            $types = $allType;
        } else {
            if (!in_array($type, $allType)) {
                $types = [$type];
            } else {
                return false;
            }
        }

        $products = Product::findAll(['goods_id' => $this->id]);
        if (!$products) {
            return false;
        }

        foreach ($products as $product) {
            $mins = ProductPrices::find(['product_id' => $product->id])->groupBy('type')->orderBy('price asc')->all();
            if (!$mins) {
                return false;
            }

            foreach ($mins as $min) {
                $update[$min->type] = $min->price;
            }
        }

        isset($update[Goods::SELL_TYPE_RETAIL]) && $this->price_retail = $update[Goods::SELL_TYPE_RETAIL];
        isset($update[Goods::SELL_TYPE_MIX]) && $this->price_mix = $update[Goods::SELL_TYPE_MIX];
        isset($update[Goods::SELL_TYPE_PACK]) && $this->price_pack = $update[Goods::SELL_TYPE_PACK];
        $this->update();
    }

    /**
     * 更新商品总库存数量和总锁定数量
     * @return type
     */
    public function updateStock() {
        $this->stock = Product::find()->where(['goods_id' => $this->id])->sum('number_stock');
        $this->stock_lock = Product::find()->where(['goods_id' => $this->id])->sum('number_lock');

        if ($this->is_auto_sale_on && ($this->stock - $this->stock_lock) > 0) {
            $this->is_on_sale = 1;
        }

        if ($this->is_auto_sale_off && ($this->stock - $this->stock_lock) <= 0) {
            $this->is_on_sale = 0;
        }

        $this->save();
    }

}
